package UDP回显服务器;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;
//UDP服务器
public class UDPClient {
    private DatagramSocket socket = null;
    public UDPClient() throws SocketException {
        socket =new DatagramSocket();
    }
    public  void start() throws IOException {
        System.out.println("客户端已启动");
        while (true){
            System.out.print(">");//等待用户输入
            Scanner scanner=new Scanner(System.in);
            String request =scanner.next();
            //构造请求包
            DatagramPacket requestPacket=new DatagramPacket(request.getBytes(),request.getBytes().length, InetAddress.getByName("127.0.0.1"),8000);
            //发送请求
            socket.send(requestPacket);
            //等待响应
            DatagramPacket responsePacket=new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            //解析响应
            String response=new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.printf("request：%s；response：%s\n",request,response);
        }
    }
    public static void main(String[] args) throws IOException {
        UDPClient client=new UDPClient();
        client.start();
    }
}
